package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.UserFavorite;
import csu.web.credit_bank.service.UserFavoritesService;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/users/{userId}/favorites")
public class UserFavoritesController {

    @Autowired
    private UserFavoritesService favoritesService;

    @PostMapping
    public Result<UserFavorite> createFavorite(@PathVariable String userId, @RequestBody UserFavorite favorite) {
        try {
            favorite.setUserId(userId);
            return Result.success("收藏成功", favoritesService.createFavorite(favorite));
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping
    public Result<List<UserFavorite>> getFavoritesByUserId(@PathVariable String userId) {
        return Result.success(favoritesService.list(new QueryWrapper<UserFavorite>().eq("user_id", userId)));
    }

    @DeleteMapping("/{favoriteId}")
    public Result<Void> deleteFavorite(@PathVariable String userId, @PathVariable String favoriteId) {
        // userId在这里可用于权限校验，确保是本人在删除自己的收藏
        boolean success = favoritesService.deleteFavorite(favoriteId);
        return success ? Result.success("取消收藏成功") : Result.failure("取消收藏失败");
    }
}
